package com.cangshi.controller;

import com.cangshi.entity.Pager;
import com.cangshi.entity.PagerSetting;
import com.cangshi.entity.User;
import com.cangshi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * Created by Eoly on 2017/6/5.
 */


@Controller
@RequestMapping("/admin")
public class AdminPageController {

    @Autowired
    private
    UserService userService;

    @Autowired
    private
    PagerSetting pagerSetting;

    @RequestMapping(value = "/login.html")
    public String loginPage() {
        return "user/login";
    }

    @RequestMapping(value = "/users/edit/{id}.html")
    public String editPage(Model model, @PathVariable Integer id) {
        model.addAttribute("user", userService.getUserById(id));
        return "user/edit";
    }

    @RequestMapping("/index.html")
    public String indexAdmin(Model model) {
        model.addAttribute("userNum", userService.getUserVolume());
        model.addAttribute("onlineNum", userService.getOnlineUsersWithKeywords(null, null, null).size());
        model.addAttribute("users", userService.getOnlineUsersWithKeywords(null, null, null));
        return "index";
    }

    @RequestMapping("/users/online.html")
    public String onlineAdmin(
            Model model,
            @RequestParam(value = "pager.offset", required = false) Integer offset,
            @RequestParam(required = false) String keywords
    ) {
        if (offset == null) {
            offset = 0;
        }
        Integer pageSize = pagerSetting.getPageSize();
        Map users = userService.getOnlineUsersWithKeywords(offset, pageSize, keywords);
        Integer userSize = userService.getOnlineUserNum(keywords);
        Pager<Map> pager = new Pager<Map>(users, pageSize, userSize, offset);
        pager.setUrl("online.html");
        pager.addParam("keywords", keywords);
        model.addAttribute("pager", pager);
        return "user/online-list";
    }
}
